package com.android.myapplication.view;

import android.Manifest;
import android.app.ActionBar;
import android.app.AlertDialog;
import android.content.ContentProvider;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.ContentObservable;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.provider.AlarmClock;
import android.provider.ContactsContract;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

import com.android.myapplication.R;
import com.android.myapplication.main.BaseActvity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static android.provider.AlarmClock.ACTION_SET_ALARM;

public class PermissionsActvity extends BaseActvity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_permissions);
        findViewById(R.id.btn_phone_info).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TelephonyManager mTm = (TelephonyManager) PermissionsActvity.this.getSystemService(Context.TELEPHONY_SERVICE);
                if (checkSelfPermission(Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(PermissionsActvity.this, "没有获取手机信息权限", Toast.LENGTH_LONG).show();
                    requestPermissions(new String[]{Manifest.permission.READ_CONTACTS,
                            Manifest.permission.WRITE_CALENDAR}, 100);
                    return;
                }
                String deviceID = mTm.getDeviceId();
                Toast.makeText(PermissionsActvity.this, "手机设备号为:" + deviceID, Toast.LENGTH_LONG).show();
            }
        });
        findViewById(R.id.btn_wifi_info).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                WifiManager wm = (WifiManager) PermissionsActvity.this.getApplicationContext().getSystemService(Context.WIFI_SERVICE);

                WifiInfo wifiInfo = wm.getConnectionInfo();
                if (wifiInfo != null) {
                    Toast.makeText(PermissionsActvity.this, "wifi 信息:" + wifiInfo.toString(), Toast.LENGTH_LONG).show();
                }
            }
        });
        findViewById(R.id.btn_content).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (android.os.Build.VERSION.SDK_INT > 23) { //检查版本号
                    if (checkSelfPermission(Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {//检查是否没有权限
                        Toast.makeText(PermissionsActvity.this, "没有获取手机信息权限", Toast.LENGTH_LONG).show();
                        if (shouldShowRequestPermissionRationale(Manifest.permission.READ_CONTACTS)) {
                            showPermissionDialog();
                        } else {
                            requestPermissions(new String[]{Manifest.permission.READ_CONTACTS}, 100);
                        }
                        return;
                    }
                }
                updateContext();
            }
        });
        findViewById(R.id.btn_clock).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setAction(ACTION_SET_ALARM);
                intent.putExtra(AlarmClock.EXTRA_MESSAGE, "上课了")
                        .putExtra(AlarmClock.EXTRA_HOUR, 4)
                        .putExtra(AlarmClock.EXTRA_MINUTES, 30);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            }
        });
        findViewById(R.id.image).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.setType("image/*");
                if (intent.resolveActivity(getPackageManager()) != null) {
                    startActivityForResult(intent, 102);
                }
            }
        });
        findViewById(R.id.btn_call_phone).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_CALL);
                intent.setData(Uri.parse("tel:" + "110"));
                if (intent.resolveActivity(getPackageManager()) != null) {
                    if (checkSelfPermission(Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                        // TODO: Consider calling
                        //    Activity#requestPermissions
                        // here to request the missing permissions, and then overriding
                        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                        //                                          int[] grantResults)
                        // to handle the case where the user grants the permission. See the documentation
                        // for Activity#requestPermissions for more details.
                        return;
                    }
                    startActivity(intent);
                }
            }
        });

    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 102 && resultCode == RESULT_OK) {
//            Bitmap thumbnail = data.getParcelableExtra("data");
//            ((ImageView)findViewById(R.id.image)).setImageBitmap(thumbnail);
            Uri fullPhotoUri = data.getData();
            ((ImageView)findViewById(R.id.image)).setImageURI(fullPhotoUri);
            // Do work with photo saved at fullPhotoUri

        }
    }

    /**
     * 5.请求权限后回调的方法
     *
     * @param requestCode  是我们自己定义的权限请求码
     * @param permissions  是我们请求的权限名称数组
     * @param grantResults 是我们在弹出页面后是否允许权限的标识数组，数组的长度对应的是权限
     *                     名称数组的长度，数组的数据0表示允许权限，-1表示我们点击了禁止权限
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions,
                                           int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        boolean hasPermissionDismiss = false;
        if (100 == requestCode) {
            for (int i = 0; i < grantResults.length; i++) {
                if (grantResults[i] == -1) {
                    hasPermissionDismiss = true; //有权限没有通过
                    break;
                }
            }
        }
        if (hasPermissionDismiss) {//如果有没有被允许的权限
            showPermissionDialog();
        } else {
            //权限已经都通过了，可以将程序继续打开了
            updateContext();
        }
    }

    private void updateContext(){
        ListView listView = findViewById(R.id.list);
        listView.setAdapter(new ArrayAdapter<String>(PermissionsActvity.this, android.R.layout.simple_list_item_1, getContactInfo()));
    }

    //读取手机里面的联系人
    public List<String> getContactInfo() {
        Log.d("AAA","Content_URI = " + ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
        Cursor cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                new String[]{"display_name", "sort_key", "contact_id",
                        "data1"}, null, null, null);
//        moveToNext方法返回的是一个boolean类型的数据
        List list = new ArrayList();
        while (cursor.moveToNext()) {
            //读取通讯录的姓名
            String name = cursor.getString(cursor
                    .getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
            //读取通讯录的号码
            String number = cursor.getString(cursor
                    .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            list.add(name + " 手机号:" + number);

        }
        cursor.close();
        return list;
    }

    /**
     * 不再提示权限时的展示对话框
     */

    private void showPermissionDialog() {
        AlertDialog mPermissionDialog = new AlertDialog.Builder(this)
                .setMessage("已禁用权限，请手动授予")
                .setPositiveButton("设置", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                        Uri packageURI = Uri.parse("package:" + getPackageName());     //去设置里面设置
                        Intent intent = new Intent(Settings.
                                ACTION_APPLICATION_DETAILS_SETTINGS, packageURI);
                        startActivity(intent);
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //关闭页面或者做其他操作
                        dialog.dismiss();
                    }
                })
                .create();

        mPermissionDialog.show();

    }

}
